﻿<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:include="./common/head :: head"></head>
<body style="background-color: #ecf0f1;">
<style type="text/css">
    .mylevel-row {
        background-color: #95a5a6;
    }

    .mylevel-row1 {
        background-color: #ecf0f1;
    }

    .dropdown-menu {
        min-width: 100px;
    }

    .dropdown-menu li {
        width: 100px;
    }
</style>

<script type="text/javascript" th:inline="javascript">
    var contextPath = [[${session.ctx}]];
    var username = [[${session.user.name}]];
    var userId = [[${session.user.id}]];
    $(function () {
        $('#cover').bootstrapTable({
            method: 'GET',
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            striped: true,                              //是否显示行间隔色
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            url: contextPath + '/categoryCover',
            height: $(window).height() - 110,
            width: $(window).width(),
            showColumns: true,
            pagination: true,
            queryParamsType: "other",
            toolbarAlign: "left",
            queryParams: function (params) {
                var param = {
                    pn: params.pageNumber,
                    ps: params.pageSize,
                    name: params.searchText,
                    userId: userId
                }
                return param;
            },
            minimumCountColumns: 2,
            pageNumber: 1,        //初始化加载第一页，默认第一页
            pageSize: 10,            //每页的记录行数（*）
            pageList: [10, 25, 50, 100],       //可供选择的每页的行数（*）
            uniqueId: "id",      //每一行的唯一标识，一般为主键列
            showExport: true,
            exportDataType: 'all',
            search: true,
            searchTimeOut: 1500,
            searchOnEnterKey: true,
            toolbar: "#toolbar",
            responseHandler: function (data) {
                var data1 = {
                    total: data.totalCount,
                    rows: data.items
                }
                return data1;
            },
            columns: [{
                field: 'id',
                title: 'ID',
                width: '5%',
                visible: false

            }, {
                field: 'coverName',
                title: '分类名称',
                align: 'center',
                valign: 'middle',
                width: '35%',

            }, {
                field: 'created',
                title: '创建时间',
                align: 'center',
                valign: 'middle',
                width: '35%',
            }, {
                field: '',
                title: '操作',
                align: 'center',
                valign: 'middle',
                width: '10%',
                formatter: function (value, row, index) {
                    var ht = $("<div></div>").append($('#operDrop')[0].outerHTML);
                    ht.attr('data-id', row.id).attr("id", "");
                    ht.find("button[id='dropdownMenu']").attr("id", "dropdownMenu" + row.id);
                    ht.find(".dropdown-menu").attr("aria-labelledby", "dropdownMenu" + row.id);
                    ht.find('.my-del').attr('onclick', "del(" + row.id + ")");
                    ht.find('.my-edit').attr('onclick', "edit(" + row.id + ")");
                    return ht.html();
                }
            }]
        });

        $("#confirmDelBtn").click(function (e) {
            var id = $('#confirmModal').data("id");
            http.del(contextPath+"/categoryCover", id, function (data) {
                if (data.success) {
                    toastr.success('删除成功');
                    $('#confirmModal').modal('hide');
                    search();
                } else {
                    toastr.warning('删除失败');
                    $('#confirmModal').modal('hide');
                }
            })
        });

        $("#editForm").bootstrapValidator({
            live: 'disabled',//验证时机，enabled是内容有变化就验证（默认），disabled和submitted是提交再验证
            excluded: [':disabled', ':hidden', ':not(:visible)'],//排除无需验证的控件，比如被禁用的或者被隐藏的
            submitButtons: '#confirmSaveBtn',//指定提交按钮，如果验证失败则变成disabled，但我没试成功，反而加了这句话非submit按钮也会提交到action指定页面
            message: '验证失败',//好像从来没出现过
            feedbackIcons: {//根据验证结果显示的各种图标
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                coverName: {
                    validators: {
                        notEmpty: {//检测非空,radio也可用
                            message: '名称必须输入'
                        },
                        threshold: 5, //有6字符以上才发送ajax请求，（input中输入一个字符，插件会向服务器发送一次，设置限制，6字符以上才开始）
                        remote: {//ajax验证。server result:{"valid",true or false} 向服务发送当前input name值，获得一个json数据。例表示正确：{"valid",true}
                            url: contextPath + '/categoryCover/validation',//验证地址
                            message: '分类名称已存在',//提示消息
                            delay: 500,//每输入一个字符，就发ajax请求，服务器压力还是太大，设置2秒发送一次ajax（默认输入一个字符，提交一次，服务器压力太大）
                            type: 'get',//请求方式
                            data: function (v) {
                                var data = v.$form.serializeJSON();
                                return {
                                    userId: userId,
                                    coverName: data.coverName,
                                    id: data.id,
                                }
                            }
                        },
                    }
                },
            }
        }).on('success.form.bv', function (e) {//点击提交之后
            e.preventDefault();
            var data = $(e.target).serializeJSON();
            if (common.isNull(data.id)) {
                data.userId = userId;
                http.add(contextPath+"/categoryCover", data, function (data) {
                    if (data.success) {
                        toastr.success('保存成功');
                        $('#editModal').modal('hide');
                        search();
                    } else {
                        toastr.warning('保存失败');
                        $('#editModal').modal('hide');
                    }
                });
            } else {
                http.update(contextPath+"/categoryCover", data, function (data) {
                    if (data.success) {
                        toastr.success('保存成功');
                        $('#editModal').modal('hide');
                        search();
                    } else {
                        toastr.warning('保存失败');
                        $('#editModal').modal('hide');
                    }
                });
            }
        });
    });

    function del(id) {
        $('#confirmModal').data("id", id).modal('show');
    }

    function edit(id) {
        if (common.isNull(id)) {
            common.clearForm("#editForm");
            $("#editUpdated").closest(".form-group").hide();
            $('#editModal').modal('show');

        } else {
            var row = $('#cover').bootstrapTable('getRowByUniqueId', id);
            $("#editForm").loadJson(row);
            $("#editUpdated").closest(".form-group").show();
            $('#editModal').data("id", id).modal('show');
        }

    }

    function search() {
        $('#cover').bootstrapTable('refresh');
    }


</script>
<div class="container-fluid">
    <header th:include="./common/header :: header"></header>
    <div class="row">
        <div th:include="./common/leftMenu :: leftMenu" class="col-md-3"></div>
        <div class="col-md-9">
            <table id="cover"></table>
        </div>
        <div id="toolbar">
            <form class="form-inline">
                <div class="form-group" style="padding-right: 50px;">
                    <button id="create" type="button" onclick="edit()" class="btn btn-success"><span
                            class="glyphicon glyphicon-plus" aria-hidden="true">&nbsp;创建分类</span></button>
                </div>
            </form>
        </div>
    </div>
    <div class="hide">
        <div id="operDrop" class="dropdown">
            <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu" data-toggle="dropdown"
                    aria-haspopup="true" aria-expanded="true">
                <span class="glyphicon glyphicon-cog"></span>&nbsp;
                <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" aria-labelledby="dropdownMenu" data-id="">
                <li><a class="my-edit" href="#"><span class="glyphicon glyphicon-edit"></span>&nbsp;修改</a></li>
                <li><a class="my-del" href="#"><span class="glyphicon glyphicon-trash"></span>&nbsp;删除</a></li>
            </ul>
        </div>
    </div>

    <!-- confirm Modal -->
    <div class="modal fade bs-example-modal-sm" id="confirmModal" tabindex="-1" role="dialog"
         aria-labelledby="confirmModalLabel">
        <div class="modal-dialog bs-example-modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="confirmModalLabel">确认删除?</h4>
                </div>
                <div class="modal-body">
                    删除分类将会将该类别的所有收藏记录删除，您确认吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button id="confirmDelBtn" type="button" class="btn btn-success">确认</button>
                </div>
            </div>
        </div>
    </div>

    <!-- edit Modal -->
    <div class="modal fade bs-example-modal-sm" id="editModal" tabindex="-1" role="dialog"
         aria-labelledby="editModalLabel">
        <div class="modal-dialog bs-example-modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="editModalLabel">收藏分类</h4>
                </div>
                <form id="editForm">
                    <div class="modal-body">
                        <input type="hidden" name="id">
                        <div class="form-group">
                            <label for="editName">分类</label>
                            <input type="text" class="form-control" id="editName" name="coverName" placeholder="分类名称">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button id="confirmSaveBtn" type="submit" class="btn btn-success">确认</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</div>
</body>
</html>